<?php

namespace zhtfrontend\models\datas;

use common\components\helpers\Fun;
use common\components\helpers\Tree;
use common\models\datas\Menu;
use yii\base\BaseObject;
use yii\db\Query;

class Assignment extends BaseObject{
    public $id;
    public $user;

    public function __construct($id, $user = null,array $config = [])
    {
        $this->id = $id;
        $this->user = $user;
        parent::__construct($config);
    }

    public function assign($items)
    {
        $manager = \Yii::$app->authManager;
        $success = 0;
        foreach ($items as $name) {
            try {
                $item = $manager->getRole($name);
                $item = $item ?: $manager->getPermission($name);
                $manager->assign($item, $this->id);
                $success++;
            } catch (\Exception $exc) {
                \Yii::error($exc->getMessage(), __METHOD__);
            }
        }
        return $success;
    }

    /**
     * Revokes a roles from a user.
     * @param array $items
     * @return integer number of successful revoke
     */
    public function revoke($items)
    {
        $manager = \Yii::$app->authManager;
        $success = 0;
        foreach ($items as $name) {
            try {
                $item = $manager->getRole($name);
                $item = $item ?: $manager->getPermission($name);
                $manager->revoke($item, $this->id);
                $success++;
            } catch (\Exception $exc) {
                \Yii::error($exc->getMessage(), __METHOD__);
            }
        }
        return $success;
    }

    public function getItems(){
        $manager = \Yii::$app->authManager;
        $available = [];
        /**foreach (array_keys($manager->getRoles()) as $name) {//获取当前所有的角色
            $available[$name] = 'role';//$available['老师']='role',s所有的
        }*/
        foreach($manager->getRoles() as $key=>$role){
            $available[$role->description.':'.$key] = 'role';
        }
        $menus = Menu::find()->where(['module'=>'branch'])->indexBy('id')->orderBy('listorder ASC,id ASC')->asArray()->all();
        $tree = (new Tree($menus))->get_tree_select();
        $assigned_tree = [];
        /**怎样能够排序排的正常点*/
        $db = Fun::getSiteDb();
        $available_menu_ids=$assigned_menu_ids=$available_pre=[];
        foreach ($manager->getPermissions() as $name=>$permission) {
            if ($name[0] != '/') {//布吉岛这个是有什么用
                $ai = (new Query())->select(['menu_id','description'])->from('{{%auth_item}}')->where(['name'=>$name])->one($db);
                $menu_id = $ai['menu_id'];
                if(!empty($menu_id) && isset($tree[$menu_id])) {
                    $available_menu_ids[] = $menu_id;
                }else{
                    $available_pre[$permission->description.':'.$name] = 'permission';
                }
                //这里对其进行重新排序
            }
        }

        $tree_keys = array_keys($tree);
        if(!empty($available_menu_ids)){
            $diff = array_diff($tree_keys,$available_menu_ids);
            if(count($diff) > 0){
                foreach($diff as $d){
                    unset($tree[$d]);//这时候的tree是正经的与权限匹配的tree
                }
            }
        }
        foreach($tree as $k=>$t){
            $ai = (new Query())->select(['name'])->from('{{%auth_item}}')->where(['menu_id'=>$k])->one($db);
            $available[$t . ':' . $ai['name']] = 'permission';
        }
        $available = array_merge($available,$available_pre);
        $assigned = [];
        foreach (array_keys($manager->getAssignments($this->id)) as $name) {//已经分配了的角色或權限，并不僅僅是角色
            /*
             * 根据名称找到对应的描述
             */
            //$ai = AuthItem::findOne(['name'=>$name]);
            $ai = (new Query())->select(['menu_id','description'])->from('{{%auth_item}}')->where(['name'=>$name])->one($db);
            $menu_id = $ai['menu_id'];
            if(!empty($menu_id) && isset($tree[$menu_id])){
                /////$assigned[$tree[$menu_id].':'.$name] = $available[$tree[$menu_id].':'.$name];
                $assigned_menu_ids[] = $menu_id;
                unset($available[$tree[$menu_id].':'.$name]);//移除相应元素，但是tree的顺序还是保持的
            }else{
                $assigned[$ai['description'].':'.$name] = $available[$ai['description'].':'.$name];
                unset($available[$ai['description'].':'.$name]);
            }
        }

        if(!empty($assigned_menu_ids)){//按顺序从tree里面取出来，保持tree的顺序
            $diff = array_diff($tree_keys,$assigned_menu_ids);
            if(count($diff) > 0){//存在属于未进行分配的权限，将其进行移除，如果diff为空的话说明都是分配的权限，整个tree都是分配的
                foreach($diff as $d){
                    unset($tree[$d]);//这时候的tree是正经的与权限匹配的tree
                }
            }
            if(count($tree) > 0){
                $assigned_tree = $tree;
                foreach($assigned_tree as $k=>$t){
                    $ai = (new Query())->select(['name'])->from('{{%auth_item}}')->where(['menu_id'=>$k])->one($db);
                    $assigned[$t . ':' . $ai['name']] = 'permission';
                }
            }
        }

        /*
         * 将字符串转为可视化的角色，将权限相关的转为可视化的菜单展示
         * 得到对应的菜单id然后生成树，值的话是需要裁剪的，添加移除的情况要申明
         */
        return [
            'available' => $available,
            'assigned' => $assigned,
        ];
    }
}